/**
* 
* Copyright [2007] [Sunny Liu]
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/
package ${appConfig.outputPackageName}.xml;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;


public class ErrorXMLSerializer extends AbstractObjectXMLSerializer {

	private static Logger log = LoggerFactory.getLogger(ErrorXMLSerializer.class);
	/**
	 * 
	 */
	public ErrorXMLSerializer() {
		super();		
	}

	public void serialize(Object object, OutputStream out) throws IOException 
	{
		serialize(0, 599, object.toString(), out);
	}

	public void serialize(int action, int status, String message,
			Object object, OutputStream out) throws IOException 
	{		
		if(object==null) 
			serialize(action, status, message, out);
		else if (object instanceof Throwable) {
			StringWriter sw = new StringWriter();
			PrintWriter pout = new PrintWriter(sw);			
			((Throwable)object).printStackTrace(pout);			
			serialize(action, status, message + "\r\n" + sw.toString(), out);
		}else{
			serialize(action, status, message + "\r\n" + object.toString(), out);
		}
	}

	public void serialize(int action, int status, String message,
			OutputStream out) throws IOException 
	{
		if(log.isDebugEnabled()) log.debug("Entering serialize(int action, int status, String message, Object object, OutputStream out)");
		if(out==null)    throw new IllegalArgumentException("OutputStream can not be null.");		
		Document doc = null;
		try {
			doc = createResponseTemplateDocument(new Integer(action), status, message);			
			serializeDocument(doc, out);
		} catch (Exception e) {			
			log.error("Failed to Serialize.", e);
			throw new IOException("Serilization Exception.");
		}
		if(log.isDebugEnabled()) log.debug("Exiting serialize(int action, int status, String message, Object object, OutputStream out)");
		

	}

	public Class supportedObject() 
	{		
		return Throwable.class;
	}

}
